package com.habdqn.studentmanager.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.github.pagehelper.PageInfo;
import com.github.xiaofan1519.verify.core.Verify;
import com.github.xiaofan1519.verify.exception.VerifyException;
import com.habdqn.studentmanager.bean.Classes;
import com.habdqn.studentmanager.bean.Product;
import com.habdqn.studentmanager.bean.Teacher;
import com.habdqn.studentmanager.bean.ajax.Response;
import com.habdqn.studentmanager.bean.ajax.RowsResponse;
import com.habdqn.studentmanager.constant.Constant;
import com.habdqn.studentmanager.constant.ErrorCode;
import com.habdqn.studentmanager.exception.StudentException;
import com.habdqn.studentmanager.service.ClassesService;
import com.habdqn.studentmanager.service.DictionaryService;
import com.habdqn.studentmanager.service.ProductService;
import com.habdqn.studentmanager.service.TeacherService;

/**
 * @author Administrator
 * 
 *         2017年5月18日
 * 
 */
@Controller
@RequestMapping("/class")
public class ClassesController {

    private static final Logger logger = LoggerFactory.getLogger(ClassesController.class);

    @Resource
    private ClassesService classesService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private DictionaryService dicService;

    @Resource
    private ProductService productService;

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(Classes bean) {
        // 没有删除需求

        return "redirect:/class/list";
    }

    @RequestMapping("/info")
    public String info(Classes bean, Model model) {

        try {
            Verify.verifyNull(bean);
            Verify.verifyNull(bean.getName());
        }
        catch (VerifyException e) {
            logger.debug("参数校验失败", e);
            model.addAttribute(Constant.ERROR_MSG, e);
            return Constant.ERROR_PAGE;
        }

        try {
            bean = classesService.find(bean);
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e);
            return Constant.ERROR_PAGE;
        }
        model.addAttribute("bean", bean);
        return "class/info";
    }

    @RequestMapping("/list")
    public String list(Classes bean, @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize, Model model) {

        if (null == pageNum) {
            pageNum = 1;
        }

        if (null == pageSize) {
            pageSize = 10;
        }

        try {
            PageInfo<Product> products = productService.findProductList(null, null, null);
            PageInfo<Classes> pageInfo = classesService.findList(bean, pageNum, pageSize);

            String className = null;
            Integer productValue = null;
            Integer statusValue = null;

            if (null != bean) {
                className = bean.getName();
                if (null != bean.getProduct()) {
                    productValue = bean.getProduct().getId();
                }
                if (null != bean.getStatus()) {
                    statusValue = bean.getStatus();
                }
            }

            model.addAttribute("products", products.getList());
            model.addAttribute("productValue", productValue);
            model.addAttribute("statusValue", statusValue);
            model.addAttribute("nameValue", className);
            model.addAttribute("pageInfo", pageInfo);
            return "class/list";
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }
    }

    /**
     * 根据条件，返回json格式的班级列表
     * 
     * @param className
     * @param productId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/lists", method = RequestMethod.GET)
    @ResponseBody
    public RowsResponse lists(@RequestParam(required = false) String className,
            @RequestParam(required = false) Integer productId, @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        if (null == pageNum) {
            pageNum = 1;
        }

        if (null == pageSize) {
            pageSize = 10;
        }

        RowsResponse rsp = new RowsResponse();
        try {
            Classes bean = new Classes();
            bean.setName(className);
            Product product = Product.make(productId, null, null);
            bean.setProduct(product);
            PageInfo<Classes> pageInfo = classesService.findList(bean, pageNum, pageSize);

            rsp.setTotal(pageInfo.getTotal());
            rsp.setRows(pageInfo.getList());
            return rsp;
        }
        catch (StudentException e) {
            rsp.setErr(ErrorCode.System_Error);
            rsp.setMsg(e.getMessage());
            return rsp;
        }
    }

    /**
     * 跳转至修改班级页面
     * 
     * @param bean
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String toEdit(Classes bean, String className, String productId, String classStatus,
            @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize,
            Model model) {

        try {
            Verify.verifyNull(bean);
            Verify.verifyLen(bean.getName(), 2, 50);

            bean = classesService.find(bean);

            if (null == bean) {
                model.addAttribute(Constant.ERROR_MSG, "该班级不存在");
                return Constant.ERROR_PAGE;
            }

            PageInfo<Product> products = productService.findProductList(null, null, null);
            model.addAttribute("products", products.getList());
        }
        catch (VerifyException e) {
            logger.debug("参数非法", e);
            model.addAttribute(Constant.ERROR_MSG, "参数非法");
            return Constant.ERROR_PAGE;
        }
        catch (StudentException e) {
            logger.error("获取班级信息失败", e);
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        model.addAttribute("bean", bean);

        model.addAttribute("className", className);
        model.addAttribute("productId", productId);
        model.addAttribute("classStatus", classStatus);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        return "class/edit";
    }

    /**
     * 更新班级
     * 
     * @param bean
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(Classes bean, @ModelAttribute("teacherIds") List<Teacher> teachers, String className,
            String productId, String classStatus, @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize, RedirectAttributes model) {
        try {
            if (null == teachers) {
                model.addAttribute(Constant.ERROR_MSG, "至少选择一名教师");
                return Constant.ERROR_PAGE;
            }

            Verify.verifyNull(bean);
            Verify.verifyNull(bean.getProduct());
            Verify.verifyNull(bean.getProduct().getId());
            Verify.verifyLen(bean.getName(), 2, 50);
            Verify.verifyLenAllowEmpty(bean.getRemarks(), 0, 500);

            classesService.update(bean);

        }
        catch (StudentException e) {
            logger.error("更新班级信息失败", e);
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        model.addAttribute("name", className);
        model.addAttribute("product.id", productId);
        model.addAttribute("status", classStatus);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        return "redirect:/class/list";
    }

    /**
     * 新增班级
     * 
     * @param bean
     * @param model
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String toAdd(Model model) {
        try {
            PageInfo<Product> products = productService.findProductList(null, null, null);

            model.addAttribute("products", products.getList());
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e);
            return Constant.ERROR_PAGE;
        }
        return "class/add";
    }

    /**
     * 搜集页面上的教师信息
     * 
     * @param teacherIds
     * @return
     */
    @ModelAttribute("teacherIds")
    public List<Teacher> getTeacherIds(@RequestParam(required = false) List<String> teacherIds) {

        if (null == teacherIds) {
            return null;
        }

        ArrayList<Teacher> teachers = new ArrayList<>();
        for (String strId : teacherIds) {
            Teacher teacher = new Teacher();
            Integer id = null;
            try {
                id = Integer.valueOf(strId);
                teacher.setId(id);
            }
            catch (NumberFormatException e) {
                logger.debug("教师编号转换失败", e);
                continue;
            }

            teachers.add(teacher);
        }

        return teachers;
    }

    /**
     * 新增班级
     * 
     * @param bean
     * @param model
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(Classes bean, @ModelAttribute("teacherIds") List<Teacher> teachers, Model model) {

        if (CollectionUtils.isEmpty(teachers)) {
            logger.debug("教师信息为空");
            model.addAttribute(Constant.ERROR_MSG, "至少选择一名教师");
            return Constant.ERROR_PAGE;
        }

        try {
            Verify.verifyNull(bean);
            Verify.verifyNull(bean.getProduct());
            Verify.verifyNull(bean.getProduct().getId());
            Verify.verifyLen(bean.getName(), 2, 50);
            Verify.verifyLenAllowEmpty(bean.getRemarks(), 0, 500);
        }
        catch (VerifyException e) {
            logger.debug("参数非法", e);
            model.addAttribute(Constant.ERROR_MSG, "参数非法");
            return Constant.ERROR_PAGE;
        }

        try {
            bean.setTeachers(teachers);
            classesService.add(bean);
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e);
            return Constant.ERROR_PAGE;
        }
        return "redirect:/class/list";
    }

    @RequestMapping(value = "/delCT")
    @ResponseBody
    public Response delCT(String className, String teacherId) {
        Response res = null;
        try {
            Verify.verifyLen(className, 1, 10);
            Verify.verifyDigits(teacherId);
            // ext2 保存教师编号
            Classes bean = new Classes();
            bean.setName(className);
            bean.setExt2(teacherId);
            classesService.delClassesTeacher(bean);
            res = new Response();
        }
        catch (VerifyException e) {
            logger.error("非法参数", e);
            res = Response.make(ErrorCode.Invalid_Argument, e.getMessage());
        }
        catch (StudentException e) {
            logger.error("删除失败", e);
            res = Response.make(ErrorCode.System_Error, e.getMessage());
        }
        return res;
    }

    @RequestMapping(value = "/addCT")
    @ResponseBody
    public Response addCT(String className, String teacherId) {
        Response res = new Response();
        try {
            Verify.verifyEmpty(className);
            Verify.verifyDigits(teacherId);
            // ext2 保存教师编号
            Classes clazz = new Classes();
            clazz.setName(className);
            clazz.setExt2(teacherId);
            classesService.addClassesTeacher(clazz);
        }
        catch (VerifyException e) {
            logger.error("非法参数", e);
            res = Response.make(ErrorCode.Invalid_Argument, e.getMessage());
        }
        catch (StudentException e) {
            logger.error("添加失败", e);
            res = Response.make(ErrorCode.System_Error, e.getMessage());
        }
        return res;
    }
}